import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import store from '../store'
import axios from '../utils/request'

Vue.use(VueRouter)

const routes = [

    {
        path: '/',
        name: 'Home',
        component: Home, //主页总布局 路由嵌套，main作为home的子路由
        children: [{
                path: '/index',
                name: 'Index',
                meta: {
                    title: '首页'
                },
                default: true,
                component: () =>
                    import ('../views/Index.vue'), //首页main页面 懒加载
            },
            {
                path: '/userCenter',
                name: 'UserCenter',
                meta: {
                    title: '个人中心'
                },
                component: () =>
                    import ('../views/UserCenter.vue'), //个人中心页面
            },
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    }
]

const router = new VueRouter({
    // mode: 'history',
    base: process.env.BASE_URL,
    routes
})
router.beforeEach((to, from, next) => {

    //当前路由是否已经获取标识符，避免重复获取，值存在vuex中
    let hasRoute = store.state.menus.hasRoute

    //获取token
    let token = localStorage.getItem("token")

    //登录页面，放行
    if (to.path == '/login') {

        next()

    } else if (!token) { //没有token，跳转回登录页面

        next({ path: '/login' })

    } else if (token && !hasRoute) { //有token，但是没有生成路由，请求后端访问路由
        //console.log("有token，但是没有生成路由，请求后端访问路由")
        //请求获取菜单，生成动态导航
        axios.get("/sys/menu/nav", {
                Headers: {
                    Authorization: localStorage.getItem('token')
                }
            })
            .then(res => {
                //拿到menulist  存入store中
                store.commit("setMenuList", res.data.data.nav);
                //拿到权限 存入store中
                store.commit("setAuthList", res.data.data.authorities);

                //动态绑定路由

                //临时路由 -- 当前路由
                let newRoutes = router.options.routes

                //1.循环拿到的导航菜单list
                res.data.data.nav.forEach(menu => {

                    //这里是写死的，只有两级导航菜单
                    //如果导航列表有子导航，循环子导航并转化成路由格式
                    if (menu.children) {
                        menu.children.forEach(e => {
                            //1.导航菜单的格式与路由的格式相似但不同，因此需要转换成路由
                            let route = menuToRoute(e)

                            //把路由添加到路由管理中
                            if (route) {
                                //上面定义的/Home为父级，/Home在这个数组下标0的位置
                                //将整个路由push到Home的children中成为其子组件
                                newRoutes[0].children.push(route)
                            }
                        })
                    }
                })

                //临时路由添加到现有的路由中
                router.addRoutes(newRoutes)

                //将hasRoute标识符改为true并存入vuex
                hasRoute = true;
                store.commit("changeHasRouteStatus", hasRoute)
            })
    }
    next()
})

//导航转换成路由
const menuToRoute = (e => {
    //如果当前列表中没有component，说明是上级菜单，不需要转换成路由
    if (!e.component) {
        return null
    }
    //转换
    let route = {
        path: e.path,
        name: e.name,
        meta: {
            icon: e.icon,
            title: e.title
        },
        // component: () =>
        //     import ('@/views/' + e.component + '.vue')
    }
    route.component = () =>
        import ('@/views/' + e.component + '.vue')
    return route
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
export default router